package com.ecocent.api;

import java.lang.reflect.Method;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

public class ServiceProxy implements MethodInterceptor {
	private Object target;

	public Object getProxy(Object target) {
		this.target = target;
		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(target.getClass());
		// 回调方法
		enhancer.setCallback(this);
		// 创建代理对象
		if(target instanceof ApiServiceProvider){
			return enhancer.create();
		}
		return enhancer.create();
	} 

	public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
		BaseResult result = null;
		Class<?> returnType = method.getReturnType();
		if (BaseResult.class.isAssignableFrom(returnType)) {
			for (int times = 0; times < 2;times++) {
				result = (BaseResult) method.invoke(this.target, args);
				if (Constants.UNLOGIN_STATUS_CODE == result.getStatuscode()||Constants.TOKEN_ERROR_CODE == result.getStatuscode()) {
					ApiContainer.getInstance().refreshLogin();
					continue;
				}
				break;
			}
		} else {
			return method.invoke(this.target, args);
		}
		return result;
	}
}
